﻿using System;
using System.Reflection;
using System.ServiceProcess;
using System.Threading;
using LiSA_Server.Base.Factories;
using LiSA_Service.Users.Actioners;

namespace LiSA_WindowsService
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            var service = new Service1();

            if (Environment.UserInteractive)
            {
                RunInteractive(service);
            }
            else
            {
                ServiceBase.Run(service);
            }
        }

        private static void RunInteractive(ServiceBase service)
        {
            var onStartMethod = typeof(ServiceBase).GetMethod(
                "OnStart",
                BindingFlags.Instance | BindingFlags.NonPublic);
            Console.WriteLine("Starting {0}...", service.ServiceName);
            onStartMethod.Invoke(service, new object[] { new string[] { } });
            Console.Write("Checking default user...");
            ActionerFactory.Instance.Get<UserActioner>().EnsureDefaultUser();
            Console.Write("\tDONE");
            Console.WriteLine();
            Console.WriteLine("Press any key to stop the service...");
            Console.ReadKey();
            Console.WriteLine();

            var onStopMethod = typeof(ServiceBase).GetMethod(
                "OnStop",
                BindingFlags.Instance | BindingFlags.NonPublic);
            Console.Write("Stopping {0}... ", service.ServiceName);
            onStopMethod.Invoke(service, null);
            Console.WriteLine("Stopped");

            Console.WriteLine("All services stopped.");

            // Keep the console alive for a second to allow the user to see the message.
            Thread.Sleep(1000);
        }
    }
}
